<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #root {
        width: 800px;
        height: 500px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/three.js/r128/three.js"></script>
    <script src="http://www.yanhuangxueyuan.com/threejs/examples/js/loaders/OBJLoader.js"></script>
    <script src="http://www.yanhuangxueyuan.com/threejs/examples/js/controls/OrbitControls.js"></script>
    <script src="http://www.yanhuangxueyuan.com/threejs/examples/js/loaders/GLTFLoader.js"></script>
    <script>
      // if (WEBGL.isWebGLAvailable() === false) {
      //   document.body.appendChild(WEBGL.getWebGLErrorMessage())
      // }
      var container, stats, controls;
      var camera, scene, renderer, light, bbox;
      var rotating = true;

      init();
      animate();

      pauseRotation();

      function init() {
        // container = document.createElement("div")
        // document.body.appendChild(container) //创建div，并加载到html里，这里的document.body可以换成你想让模型加载的地方。
        container = document.getElementById("root");

        scene = new THREE.Scene();
        bbox = new THREE.Box3();

        scene.background = new THREE.Color("black");
        light = new THREE.HemisphereLight(0xbbbbff, 0x444422, 1.5);
        light.position.set(0, 1, 0);
        scene.add(light);
        // var loader = new THREE.GLTFLoader()
        var loader = new THREE.OBJLoader();
        // 没有材质文件，系统自动设置Phong网格材质
        var color = new THREE.Color("red");
        var color1 = new THREE.Color("#d1d13d");
        var color2 = new THREE.Color("red");
        var color3 = new THREE.Color("yellow");
        var color4 = new THREE.Color("black");
        var color5 = new THREE.Color("blue");
        var color6 = new THREE.Color("black");
        var color7 = new THREE.Color("pink");
        var color9 = new THREE.Color("rgba(100,100,100,0.1)");
        var raycaster = new THREE.Raycaster();

        loader.load("./public/productliine.obj", function (obj) {
          // obj.traverse(function (child) {
          //   // if (child instanceof THREE.Mesh) {
          //   //   child.material.ambient.setHex(0xff0000)
          //   //   child.material.color.setHex(0x00ff00)
          //   // }
          //   child.color = color
          // })

          // scene.add(obj)
          // obj.position.y = 0
          // 控制台查看返回结构：包含一个网格模型Mesh的组Group
          console.log(obj);
          // 查看加载器生成的材质对象：MeshPhongMaterial
          // console.log(obj.children[0].material,'-------------')
          let obj1 = obj.children[0].material;
          for (let i = 0; i < obj.children[0].material.length; i++) {
            console.log(obj1[i]);
            if (obj1[i].name === "Material_0") {

              obj1[i].color = color;
            } else if ((obj1[i].name = "Material_2")) {
              obj1[i].color = color1;
            }
          }
          scene.add(obj1);
          // 加载后的一些编辑操作
          obj1.children[0].scale.set(0.1, 0.1, 0.1); //网格模型缩放
          obj1.children[0].geometry.center(); //网格模型的几何体居中
          // obj.children[0].material.color.set("black") //设置材质颜色
        });
        var getRandomColor = function () {
          return (
            "#" +
            (function (color) {
              return (color += "0123401234abcabc"[
                Math.floor(Math.random() * 16)
              ]) && color.length == 6
                ? color
                : arguments.callee(color);
            })("")
          );
        };
        var getRandomColor1 = function () {
          return (
            "#" +
            (function (color) {
              return (color += "5678956789defdef"[
                Math.floor(Math.random() * 16)
              ]) && color.length == 6
                ? color
                : arguments.callee(color);
            })("")
          );
        };

        // loader.load(
        //   "./public/productliine.glb",
        //   function (gltf) {
        //     gltf.scene.name = "3dmodel"
        //     let index = 0
        //     gltf.scene.traverse(function (child) {
        //       if (child.isMesh) {
        //         index++
        //         child.material.emissive = child.material.color
        //         child.material.emissiveMap = child.material.map
        //         if (index % 2 === 0) {
        //           child.material.color.set(
        //             `rgba(13, 96, 255,${Math.random() * (1 - 0.8) + 0.8})`
        //           )
        //         }

        //         // }else {
        //         //   child.material.color.set(0xffffff)
        //         // }

        //         child.material.transparent = true
        //         child.material.opacity = 0.8
        //       }
        //     })
        //     this.setContent(gltf.scene)
        //     console.log(index)

        //     scene.add(gltf.scene)
        //   },
        //   undefined,
        //   function (e) {
        //     console.error(e)
        //   }
        // )

        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.gammaOutput = true;
        container.appendChild(renderer.domElement);
        window.addEventListener("resize", onWindowResize, false);

        camera = new THREE.PerspectiveCamera(
          45, // 控制摄像头的远近
          window.innerWidth / window.innerHeight,
          1,
          4000
        );
        camera.position.z = 7;

        controls = new THREE.OrbitControls(camera);
        // to disable pan
        controls.enablePan = false;
        // to disable zoom
        controls.enableZoom = true; // 允许放大缩小
        controls.target.set(0, 0, 0);
        controls.update();
      }

      function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      }
      //
      function animate() {
        requestAnimationFrame(animate);
        if (rotating) {
          scene.rotation.y += -0.002;
        } else {
          scene.rotation.y = scene.rotation.y;
        }

        renderer.render(scene, camera);
      }

      function pauseRotation() {
        var modelBorder = document.getElementById("root");
        modelBorder.addEventListener("mouseenter", function (event) {
          rotating = false;
        });
        modelBorder.addEventListener("mouseleave", function (event) {
          rotating = true;
        });
        modelBorder.addEventListener(
          "touchmove",
          function (e) {
            rotating = false;
          },
          false
        );
        modelBorder.addEventListener(
          "touchstart",
          function (e) {
            rotating = false;
          },
          false
        );
        modelBorder.addEventListener(
          "touchend",
          function (e) {
            rotating = true;
          },
          false
        );
      }

      function setContent(object) {
        object.updateMatrixWorld();
        const box = new THREE.Box3().setFromObject(object);
        const size = box.getSize(new THREE.Vector3()).length();
        const boxSize = box.getSize();
        const center = box.getCenter(new THREE.Vector3());

        object.position.x += object.position.x - center.x;
        object.position.y += object.position.y - center.y;
        object.position.z += object.position.z - center.z;

        this.camera.position.copy(center);
        if (boxSize.x > boxSize.y) {
          this.camera.position.z = boxSize.x * -2.85;
        } else {
          this.camera.position.z = boxSize.y * -2.85;
        }
        this.camera.lookAt(0, 0, 0);
      }
    </script>
  </body>
</html>
